{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g_nWetWWd_ns"
      },
      "source": [
        "##### Copyright 2024 The AI Edge Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "2pHVBk_seED1"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M7vSdG6sAIQn"
      },
      "source": [
        "# TensorFlow Lite Model Analyzer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fwc5GKHBASdc"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/lite/guide/model_analyzer\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/guide/model_analyzer.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/guide/model_analyzer.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/lite/g3doc/guide/model_analyzer.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9ee074e4"
      },
      "source": [
        "TensorFlow Lite Model Analyzer API helps you analyze models in TensorFlow Lite format by listing a model's structure.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JKwW0VfDKMWS"
      },
      "source": [
        "## Model Analyzer API\n",
        "\n",
        "The following API is available for the TensorFlow Lite Model Analyzer.\n",
        "\n",
        "```\n",
        "tf.lite.experimental.Analyzer.analyze(model_path=None,\n",
        "                                      model_content=None,\n",
        "                                      gpu_compatibility=False)\n",
        "```\n",
        "\n",
        "You can find the API details from https://www.tensorflow.org/api_docs/python/tf/lite/experimental/Analyzer or run `help(tf.lite.experimental.Analyzer.analyze)` from a Python terminal.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qi8Vk4_065jN"
      },
      "source": [
        "## Basic usage with simple Keras model\n",
        "\n",
        "The following code shows basic usage of Model Analyzer. It shows contents of the converted Keras model in TFLite model content, formatted as a flatbuffer object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_jkg6UNtdz8c"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "model = tf.keras.models.Sequential([\n",
        "  tf.keras.layers.Flatten(input_shape=(128, 128)),\n",
        "  tf.keras.layers.Dense(256, activation='relu'),\n",
        "  tf.keras.layers.Dropout(0.2),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()\n",
        "\n",
        "tf.lite.experimental.Analyzer.analyze(model_content=fb_model)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pe_ZU5Zy7PeH"
      },
      "source": [
        "## Basic usage with MobileNetV3Large Keras model\n",
        "\n",
        "This API works with large models such as MobileNetV3Large. Since the output is large, you might want to browse it with your favorite text editor."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QFywJ_g56VW5"
      },
      "outputs": [],
      "source": [
        "model = tf.keras.applications.MobileNetV3Large()\n",
        "fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()\n",
        "\n",
        "tf.lite.experimental.Analyzer.analyze(model_content=fb_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4BGqG2j9yqRf"
      },
      "source": [
        "## Check GPU delegate compatibility\n",
        "\n",
        "The ModelAnalyzer API provides a way to check the [GPU delegate](https://www.tensorflow.org/lite/performance/gpu) compatibility of the given model by providing `gpu_compatibility=True` option.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sVGC1oX33RkV"
      },
      "source": [
        "### Case 1: When model is incompatibile\n",
        "\n",
        "The following code shows a way to use `gpu_compatibility=True` option for simple tf.function which uses `tf.slice` with a 2D tensor and `tf.cosh` which are not compatible with GPU delegate.\n",
        "\n",
        "You will see `GPU COMPATIBILITY WARNING` per every node which has compatibility issue(s)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9GEg5plIzD-3"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "@tf.function(input_signature=[\n",
        "    tf.TensorSpec(shape=[4, 4], dtype=tf.float32)\n",
        "])\n",
        "def func(x):\n",
        "  return tf.cosh(x) + tf.slice(x, [1, 1], [1, 1])\n",
        "\n",
        "converter = tf.lite.TFLiteConverter.from_concrete_functions(\n",
        "    [func.get_concrete_function()], func)\n",
        "converter.target_spec.supported_ops = [\n",
        "    tf.lite.OpsSet.TFLITE_BUILTINS,\n",
        "    tf.lite.OpsSet.SELECT_TF_OPS,\n",
        "]\n",
        "fb_model = converter.convert()\n",
        "\n",
        "tf.lite.experimental.Analyzer.analyze(model_content=fb_model, gpu_compatibility=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BFU7HYb_2a8M"
      },
      "source": [
        "### Case 2: When model is compatibile\n",
        "\n",
        "In this example, the given model is compatbile with GPU delegate.\n",
        "\n",
        "**Note:** Even though the tool doesn't find any compatibility issue, it doesn't guarantee that your model works well with GPU delegate on every device. There could be some runtime incompatibililty happen such as missing `CL_DEVICE_IMAGE_SUPPORT` feature by target OpenGL backend.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "85RgG6tQ3ABT"
      },
      "outputs": [],
      "source": [
        "model = tf.keras.models.Sequential([\n",
        "  tf.keras.layers.Flatten(input_shape=(128, 128)),\n",
        "  tf.keras.layers.Dense(256, activation='relu'),\n",
        "  tf.keras.layers.Dropout(0.2),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "fb_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()\n",
        "\n",
        "tf.lite.experimental.Analyzer.analyze(model_content=fb_model, gpu_compatibility=True)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "model_analyzer.ipynb",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
